package com.itheima.health.service.impl;


import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

/**
 * @author spt
 * @description
 * @date 2019/9/29
 **/
@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    /**
     * 根据预约日期查询是否做过预约设置
     * @param orderDate
     * @return
     */

    @Override
    public OrderSetting getOrderSettingByOrderDate(Date orderDate) {
        OrderSetting orderSetting = orderSettingDao.selectByDate(orderDate);
        return orderSetting;
    }
    /**
     * 更新预约设置的已预约人数
     * @param orderSetting
     */
    @Override
    public void updateReservationsById(OrderSetting orderSetting){
        orderSettingDao.updateReservationsById(orderSetting);
    }





    @SneakyThrows
    @Override
    public List<OrderSetting> listOrderSettings(String date) {
        List<OrderSetting> orderSettings = orderSettingDao.listOrderSettings(date);
        return orderSettings;
    }

    /**
     * 根据日期修改人数
     *
     * @param orderDate
     * @param number
     */
    @Override
    @Transactional
    public void updateNumberByDate(Date orderDate, Integer number) {
        //要判断查出来的orderSetting是不是存在
        OrderSetting orderSetting = orderSettingDao.selectByDate(orderDate);

        if (orderSetting == null) {
            //如果没有设置，要添加最大预约人数
            orderSettingDao.insertByDate(orderDate, number);
        } else {
            //获取已预约人数进行比较
            int reservations = orderSetting.getReservations();
            if (number >= reservations) {
                //设置了，要更新最大预约人数
                orderSettingDao.updateNumberByDate(orderDate, number);
            } else {
                throw new BusinessRuntimeException("修改可预约人数失败");
            }
        }
    }
}
